/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package da;

import da.exceptions.IllegalOrphanException;
import da.exceptions.NonexistentEntityException;
import da.exceptions.PreexistingEntityException;
import da.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Account;
import java.util.ArrayList;
import java.util.List;
import entities.Complain;
import entities.Department;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author THOHCGC00177
 */
public class DepartmentJpaController implements Serializable {

    public DepartmentJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Department department) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (department.getAccountList() == null) {
            department.setAccountList(new ArrayList<Account>());
        }
        if (department.getComplainList() == null) {
            department.setComplainList(new ArrayList<Complain>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<Account> attachedAccountList = new ArrayList<Account>();
            for (Account accountListAccountToAttach : department.getAccountList()) {
                accountListAccountToAttach = em.getReference(accountListAccountToAttach.getClass(), accountListAccountToAttach.getId());
                attachedAccountList.add(accountListAccountToAttach);
            }
            department.setAccountList(attachedAccountList);
            List<Complain> attachedComplainList = new ArrayList<Complain>();
            for (Complain complainListComplainToAttach : department.getComplainList()) {
                complainListComplainToAttach = em.getReference(complainListComplainToAttach.getClass(), complainListComplainToAttach.getId());
                attachedComplainList.add(complainListComplainToAttach);
            }
            department.setComplainList(attachedComplainList);
            em.persist(department);
            for (Account accountListAccount : department.getAccountList()) {
                Department oldDepartmentIdOfAccountListAccount = accountListAccount.getDepartmentId();
                accountListAccount.setDepartmentId(department);
                accountListAccount = em.merge(accountListAccount);
                if (oldDepartmentIdOfAccountListAccount != null) {
                    oldDepartmentIdOfAccountListAccount.getAccountList().remove(accountListAccount);
                    oldDepartmentIdOfAccountListAccount = em.merge(oldDepartmentIdOfAccountListAccount);
                }
            }
            for (Complain complainListComplain : department.getComplainList()) {
                Department oldDepartmentIdOfComplainListComplain = complainListComplain.getDepartmentId();
                complainListComplain.setDepartmentId(department);
                complainListComplain = em.merge(complainListComplain);
                if (oldDepartmentIdOfComplainListComplain != null) {
                    oldDepartmentIdOfComplainListComplain.getComplainList().remove(complainListComplain);
                    oldDepartmentIdOfComplainListComplain = em.merge(oldDepartmentIdOfComplainListComplain);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findDepartment(department.getId()) != null) {
                throw new PreexistingEntityException("Department " + department + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Department department) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Department persistentDepartment = em.find(Department.class, department.getId());
            List<Account> accountListOld = persistentDepartment.getAccountList();
            List<Account> accountListNew = department.getAccountList();
            List<Complain> complainListOld = persistentDepartment.getComplainList();
            List<Complain> complainListNew = department.getComplainList();
            List<String> illegalOrphanMessages = null;
            for (Account accountListOldAccount : accountListOld) {
                if (!accountListNew.contains(accountListOldAccount)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Account " + accountListOldAccount + " since its departmentId field is not nullable.");
                }
            }
            for (Complain complainListOldComplain : complainListOld) {
                if (!complainListNew.contains(complainListOldComplain)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Complain " + complainListOldComplain + " since its departmentId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Account> attachedAccountListNew = new ArrayList<Account>();
            for (Account accountListNewAccountToAttach : accountListNew) {
                accountListNewAccountToAttach = em.getReference(accountListNewAccountToAttach.getClass(), accountListNewAccountToAttach.getId());
                attachedAccountListNew.add(accountListNewAccountToAttach);
            }
            accountListNew = attachedAccountListNew;
            department.setAccountList(accountListNew);
            List<Complain> attachedComplainListNew = new ArrayList<Complain>();
            for (Complain complainListNewComplainToAttach : complainListNew) {
                complainListNewComplainToAttach = em.getReference(complainListNewComplainToAttach.getClass(), complainListNewComplainToAttach.getId());
                attachedComplainListNew.add(complainListNewComplainToAttach);
            }
            complainListNew = attachedComplainListNew;
            department.setComplainList(complainListNew);
            department = em.merge(department);
            for (Account accountListNewAccount : accountListNew) {
                if (!accountListOld.contains(accountListNewAccount)) {
                    Department oldDepartmentIdOfAccountListNewAccount = accountListNewAccount.getDepartmentId();
                    accountListNewAccount.setDepartmentId(department);
                    accountListNewAccount = em.merge(accountListNewAccount);
                    if (oldDepartmentIdOfAccountListNewAccount != null && !oldDepartmentIdOfAccountListNewAccount.equals(department)) {
                        oldDepartmentIdOfAccountListNewAccount.getAccountList().remove(accountListNewAccount);
                        oldDepartmentIdOfAccountListNewAccount = em.merge(oldDepartmentIdOfAccountListNewAccount);
                    }
                }
            }
            for (Complain complainListNewComplain : complainListNew) {
                if (!complainListOld.contains(complainListNewComplain)) {
                    Department oldDepartmentIdOfComplainListNewComplain = complainListNewComplain.getDepartmentId();
                    complainListNewComplain.setDepartmentId(department);
                    complainListNewComplain = em.merge(complainListNewComplain);
                    if (oldDepartmentIdOfComplainListNewComplain != null && !oldDepartmentIdOfComplainListNewComplain.equals(department)) {
                        oldDepartmentIdOfComplainListNewComplain.getComplainList().remove(complainListNewComplain);
                        oldDepartmentIdOfComplainListNewComplain = em.merge(oldDepartmentIdOfComplainListNewComplain);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = department.getId();
                if (findDepartment(id) == null) {
                    throw new NonexistentEntityException("The department with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Department department;
            try {
                department = em.getReference(Department.class, id);
                department.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The department with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Account> accountListOrphanCheck = department.getAccountList();
            for (Account accountListOrphanCheckAccount : accountListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Department (" + department + ") cannot be destroyed since the Account " + accountListOrphanCheckAccount + " in its accountList field has a non-nullable departmentId field.");
            }
            List<Complain> complainListOrphanCheck = department.getComplainList();
            for (Complain complainListOrphanCheckComplain : complainListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Department (" + department + ") cannot be destroyed since the Complain " + complainListOrphanCheckComplain + " in its complainList field has a non-nullable departmentId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(department);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Department> findDepartmentEntities() {
        return findDepartmentEntities(true, -1, -1);
    }

    public List<Department> findDepartmentEntities(int maxResults, int firstResult) {
        return findDepartmentEntities(false, maxResults, firstResult);
    }

    private List<Department> findDepartmentEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Department.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Department findDepartment(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Department.class, id);
        } finally {
            em.close();
        }
    }

    public int getDepartmentCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Department> rt = cq.from(Department.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
